package com.cema.manage.project.android.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cema.manage.common.exception.BizException;
import com.cema.manage.common.exception.RiskException;
import com.cema.manage.common.utils.StringUtils;
import com.cema.manage.project.android.model.LoginVo;
import com.cema.manage.project.android.model.PageVo;
import com.cema.manage.project.android.model.result.BizFriend;
import com.cema.manage.project.android.model.result.BizRankingList;
import com.cema.manage.project.android.service.BizUserService;
import com.cema.manage.project.enums.CallbackAdRecordEnum;
import com.cema.manage.project.enums.MoneyTypeEnum;
import com.cema.manage.project.enums.RedisEnum;
import com.cema.manage.project.enums.UserEffectiveStatusEnum;
import com.cema.manage.project.manage.adRecord.domain.AdRecord;
import com.cema.manage.project.manage.adRecord.service.IAdRecordService;
import com.cema.manage.project.manage.friend.domain.Friend;
import com.cema.manage.project.manage.friend.service.IFriendService;
import com.cema.manage.project.manage.rewardRecord.domain.RewardRecord;
import com.cema.manage.project.manage.rewardRecord.service.IRewardRecordService;
import com.cema.manage.project.manage.userFeedback.domain.UserFeedback;
import com.cema.manage.project.manage.userFeedback.service.IUserFeedbackService;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.manage.users.mapper.UsersMapper;
import com.cema.manage.project.manage.users.service.IUsersService;
import com.cema.manage.project.system.user.domain.User;
import com.cema.manage.project.system.user.mapper.UserMapper;
import com.cema.manage.project.util.DateUtils;
import com.cema.manage.project.util.HttpUtil;
import com.cema.manage.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户账号 服务层实现
 *
 * @author reasahi
 * @date 2024-07-08
 */
@Service
public class BizUserServiceImpl extends ServiceImpl<UsersMapper, Users> implements BizUserService {
    private static final Logger log = LoggerFactory.getLogger(BizUserServiceImpl.class);

    @Resource
    private IUsersService iUsersService;

    @Resource
    private IFriendService iFriendService;

    @Resource
    private IUserFeedbackService iUserFeedbackService;

    @Resource
    private IAdRecordService adRecordService;

    @Resource
    private IRewardRecordService rewardRecordService;

    @Resource
    private RedisService redisService;

    @Resource
    private UserMapper userMapper;

    @Override
    public Users registerUser(LoginVo loginVo, String ip) {
        //第一步请求的地址，appid和secret替换成自己申请下来的即可，code就是手机获取到的参数
        String appId = (String) redisService.get(RedisEnum.WX_LOGIN_APP_ID.getKey() + loginVo.getUvChannel());
        if (StrUtil.isEmpty(appId)) {
            throw new BizException("请配置微信登录");
        }
        checkShuangQing(loginVo);
        String appSecret = (String) redisService.get(RedisEnum.WX_LOGIN_APP_SECRET.getKey() + loginVo.getUvChannel());
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + loginVo.getWxCode() + "&grant_type=authorization_code";
        //使用http请求数据，其中，HttpUtil是自己的辅助类，代码会放到后面
        String result = HttpUtil.sendGet(url, "utf-8");
        JSONObject resultJson = JSONUtil.parseObj(result);
        System.out.println(result);
        //处理不正确的code情况，我只判断了400029，如果有完整微信错误字典，可以走框架流程
        if (resultJson.containsKey("errcode") && resultJson.getInt("errcode") == 40029) {
            throw new BizException("code不合法");
        }
        String openid = "";
        String unionid = "";
        if (resultJson.containsKey("access_token")) {
            //该APP下使用微信登录获取到的唯一值
            openid = resultJson.getStr("openid");
            unionid = resultJson.getStr("unionid");
        }
        if (StrUtil.isEmpty(openid)) {
            throw new BizException("授权登录失败");
        }
        //通过Openid查找用户
        EntityWrapper<Users> wrapper = new EntityWrapper<>();
        wrapper.eq("openid", openid);
        Users users = iUsersService.selectOne(wrapper);
        if (ObjectUtil.isNotNull(users)) {
            String oaId = users.getOaid();
            String deviceId = users.getDeviceId();
            //验证双清
            if (!loginVo.getDeviceId().equals(deviceId) && !loginVo.getOaid().equals(oaId)) {
                String shuangQing = (String) redisService.get(RedisEnum.RISK_SHUANG_QING.getKey()+loginVo.getUvChannel());
                //获取风控
                String redisKey = openid + StrUtil.COMMA + loginVo.getOaid() + StrUtil.COMMA + loginVo.getDeviceId();
                if (StrUtil.isNotEmpty(shuangQing)) {
                    String value = (String) redisService.get(redisKey);
                    if (StrUtil.isEmpty(value)) {
                        redisService.set(redisKey, redisKey);
                    }
                    verifyRiskControl(openid, shuangQing);
                }
                String value = (String) redisService.get(redisKey);
                String[] valueStr = value.split(StrUtil.COMMA);
                if (valueStr[1].equals(loginVo.getOaid()) && valueStr[2].equals(loginVo.getDeviceId())) {
                    //绑定新的微信ID
                    EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
                    entityWrapper.eq("device_id", loginVo.getDeviceId());
                    Users usersByDeviceId = iUsersService.selectOne(entityWrapper);
                    if (ObjectUtil.isNotNull(usersByDeviceId)) {
                        //更新设备Id
                        Users usersById = new Users();
                        usersById.setOpenid("unknown");
                        usersById.setOaid("unknown");
                        usersById.setDeviceId("unknown");
                        usersById.setId(users.getId());
                        iUsersService.updateById(usersById);

                        Users sqUsers = new Users();
                        sqUsers.setOaid(loginVo.getOaid());
                        sqUsers.setOpenid(openid);
                        sqUsers.setDeviceId(loginVo.getDeviceId());
                        sqUsers.setId(usersByDeviceId.getId());
                        iUsersService.updateById(sqUsers);
                    } else {
                        Users sqUsers = new Users();
                        sqUsers.setOaid(loginVo.getOaid());
                        sqUsers.setOpenid(openid);
                        sqUsers.setDeviceId(loginVo.getDeviceId());
                        sqUsers.setId(users.getId());
                        iUsersService.updateById(sqUsers);
                    }
                    users.setOpenid(openid);
                    users.setOaid(loginVo.getOaid());
                    users.setDeviceId(loginVo.getDeviceId());
                    redisService.remove(openid);
                    redisService.remove(redisKey);
                } else {
                    redisService.remove(openid);
                    redisKey = openid + StrUtil.COMMA + loginVo.getOaid() + StrUtil.COMMA + loginVo.getDeviceId();
                    redisService.set(redisKey, redisKey);
                    verifyRiskControl(openid, shuangQing);
                }
            }
            //验证单清
            else if (!loginVo.getOaid().equals(oaId)) {
                checkSingleClear(loginVo, users, openid);
            }
            return users;
        }
        // 通过设备查找用户
        EntityWrapper<Users> userEntityWrapper = new EntityWrapper<>();
        userEntityWrapper.eq("device_id", loginVo.getDeviceId());
        Users deviceUsers = iUsersService.selectOne(userEntityWrapper);
        if (ObjectUtil.isNotNull(deviceUsers)) {
            String deviceUsersOpenid = deviceUsers.getOpenid();
            if (StrUtil.isNotEmpty(deviceUsersOpenid)) {
                throw new BizException("超过Aid设备数量限制");
            }
            Users updateUsers = new Users();
            updateUsers.setId(deviceUsers.getId());
            updateUsers.setUnionid(unionid);
            updateUsers.setOaid(loginVo.getOaid());
            updateUsers.setOpenid(openid);
            updateById(updateUsers);
            deviceUsers.setUnionid(unionid);
            deviceUsers.setOaid(loginVo.getOaid());
            deviceUsers.setOpenid(openid);
            return deviceUsers;
        }
        //注册
        Users usersInsert = new Users();
        usersInsert.setDeviceId(loginVo.getDeviceId());
        usersInsert.setUnionid(unionid);
        usersInsert.setOaid(loginVo.getOaid());
        usersInsert.setOpenid(openid);
        usersInsert.setNickname(isValidNickName());
        //需要验重
        usersInsert.setCode(isValidCode());
        usersInsert.setJoinIp(ip);
        usersInsert.setLoginIp(ip);
        usersInsert.setLoginTime(new Date());
        usersInsert.setLoginDayNumber(1);
        usersInsert.setLoginInDayNumber(1);
        Users fUsers = null;
        String fCode = loginVo.getCode();
        if (StringUtils.isNotEmpty(fCode)) {
            EntityWrapper<Users> fWrapper = new EntityWrapper<>();
            fWrapper.eq("code", fCode);
            fUsers = iUsersService.selectOne(fWrapper);
            if (ObjectUtil.isNotNull(fUsers)) {
                usersInsert.setUsParentId(fUsers.getId());
            }
        }

        iUsersService.insert(usersInsert);
        Users returnUses = iUsersService.selectOne(wrapper);
        //绑定师徒关系
        if (ObjectUtil.isNotNull(fUsers)) {
            Friend friend = new Friend();
            friend.setUsId(returnUses.getId());
            friend.setFusId(fUsers.getId());
            iFriendService.insert(friend);
        }
        return returnUses;
    }

    @Override
    @Transactional
    public Users registerUserNew(LoginVo loginVo, String ip) {
        EntityWrapper<Users> wrapper = new EntityWrapper<>();
        wrapper.eq("device_id", loginVo.getDeviceId());
        Users users = iUsersService.selectOne(wrapper);
        //处理单双清
        checkShuangQing(loginVo);
        if (ObjectUtil.isNotNull(users)) {
            String oaId = users.getOaid();
            if (StrUtil.isEmpty(oaId)) {
                Users sqUsers = new Users();
                sqUsers.setOaid(loginVo.getOaid());
                sqUsers.setId(users.getId());
                users.setOaid(loginVo.getOaid());
                iUsersService.updateById(sqUsers);
                return users;
            }
            if (!loginVo.getOaid().equals(oaId)) {
                checkSingleClear(loginVo, users, oaId);
            }
            return users;
        }
        //注册
        Users usersInsert = new Users();
        usersInsert.setDeviceId(loginVo.getDeviceId());
        usersInsert.setNickname(isValidNickName());
        //需要验重
        usersInsert.setCode(isValidCode());
        usersInsert.setJoinIp(ip);
        usersInsert.setOaid(loginVo.getOaid());
        usersInsert.setLoginIp(ip);
        usersInsert.setLoginTime(new Date());
        usersInsert.setLoginDayNumber(1);
        usersInsert.setLoginInDayNumber(1);
        Users fUsers = null;
        String fCode = loginVo.getCode();
        if (StringUtils.isNotEmpty(fCode)) {
            EntityWrapper<Users> fWrapper = new EntityWrapper<>();
            fWrapper.eq("code", fCode);
            fUsers = iUsersService.selectOne(fWrapper);
            if (ObjectUtil.isNotNull(fUsers)) {
                usersInsert.setUsParentId(fUsers.getId());
            }
        }

        iUsersService.insert(usersInsert);
        Users returnUses = iUsersService.selectOne(wrapper);
        //绑定师徒关系
        if (ObjectUtil.isNotNull(fUsers)) {
            Friend friend = new Friend();
            friend.setUsId(returnUses.getId());
            friend.setFusId(fUsers.getId());
            iFriendService.insert(friend);
        }
        return returnUses;
    }

    private void checkSingleClear(LoginVo loginVo, Users users, String oaId) {
        String singleClear = (String) redisService.get(RedisEnum.RISK_SINGLE_CLEAR.getKey()+loginVo.getUvChannel());
        String redisKey = RedisEnum.APP_OAID.getKey() + StrUtil.COMMA + users.getId();
        if (StrUtil.isNotEmpty(singleClear)) {
            String oaid = (String) redisService.get(redisKey);
            if (StrUtil.isEmpty(oaid)) {
                redisService.set(redisKey, loginVo.getOaid());
            }
            verifyRiskControl(oaId, singleClear);
        }
        //验证是否满足解封条件
        String oaid = (String) redisService.get(redisKey);
        if (loginVo.getOaid().equals(oaid.split(StrUtil.COMMA)[0])) {
            //更新oaId
            Users sqUsers = new Users();
            sqUsers.setOaid(loginVo.getOaid());
            sqUsers.setId(users.getId());
            users.setOaid(loginVo.getOaid());
            iUsersService.updateById(sqUsers);
            redisService.remove(redisKey);
            redisService.remove(oaId);
        } else {
            redisService.remove(oaId);
            redisService.set(redisKey, loginVo.getOaid());
            verifyRiskControl(oaId, singleClear);
        }
    }


    @Override
    public synchronized boolean userFeedback(Integer usId, String content) {
        UserFeedback userFeedback = new UserFeedback();
        userFeedback.setUsId(usId);
        userFeedback.setUfContent(content);
        return iUserFeedbackService.insert(userFeedback);
    }

    @Override
    public Map<String, Integer> countFriend(Integer usId) {
        Map<String, Integer> map = new HashMap<>(3);
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        Users users = new Users();
        users.setUsParentId(usId);
        entityWrapper.setEntity(users);
        entityWrapper.setSqlSelect("effective");
        List<Users> usersList = iUsersService.selectList(entityWrapper);
        int count = 0;
        int yesCount = 0;
        int noCount = 0;
        if (ObjectUtil.isNotNull(usersList)) {
            count = usersList.size();
            List<Users> yesList = usersList.stream().filter(users1 -> UserEffectiveStatusEnum.USER_EFFECTIVE_STATUS_NORMAL.getValue().equals(users1.getEffective())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(yesList)) {
                yesCount = yesList.size();
            }
            List<Users> noList = usersList.stream().filter(users1 -> UserEffectiveStatusEnum.USER_EFFECTIVE_STATUS_VIOLATION.getValue().equals(users1.getEffective())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(noList)) {
                noCount = noList.size();
            }
        }
        //总数
        map.put("count", count);
        //有效
        map.put("yesCount", yesCount);
        //无效
        map.put("noCount", noCount);
        return map;
    }

    @Override
    public List<BizFriend> queryBizFriend(Integer usId, Integer effective, PageVo pageVo) {
        return iFriendService.queryBizFriend(usId, effective, pageVo);
    }

    @Override
    public void taskSignIn() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        if (!(hour == 23 && minute == 59)) {
            return;
        }
        Users usersUp = new Users();
        usersUp.setSignIdDayNumber(0);
        usersUp.setSignIn(0);

        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        Users usersWhere = new Users();
        usersWhere.setSignIdDayNumber(8);
        entityWrapper.setEntity(usersWhere);
        iUsersService.update(usersUp, entityWrapper);

        EntityWrapper<Users> usersEntityWrapper = new EntityWrapper<>();
        usersEntityWrapper.eq("sign_in", 0);
        usersEntityWrapper.gt("sign_id_day_number", 0);
        iUsersService.update(usersUp, usersEntityWrapper);

        //重置今天签到次数
        Users signUsers = new Users();
        signUsers.setSignIn(0);
        EntityWrapper<Users> signUsersEntityWrapper = new EntityWrapper<>();
        usersEntityWrapper.eq("sign_In", 1);
        iUsersService.update(signUsers, signUsersEntityWrapper);
    }

    @Override
    public boolean saveAfbInfo(Users users, String uvChannel) {
        //验证支付宝
        EntityWrapper<Users> usersEntityWrapper = new EntityWrapper<>();
        usersEntityWrapper.eq("afb_phone", users.getAfbPhone());
        int count = iUsersService.selectCount(usersEntityWrapper);
        String zfb = (String) redisService.get(RedisEnum.BIND_ZFB.getKey() + uvChannel);
        if (count >= Integer.parseInt(zfb)) {
            throw new BizException("同一个支付宝最多绑定" + Integer.parseInt(zfb) + "个账号");
        }
        Users userUpdate = new Users();
        userUpdate.setId(users.getId());
        userUpdate.setAfbName(users.getAfbName());
        userUpdate.setAfbPhone(users.getAfbPhone());
        boolean flag = iUsersService.updateById(userUpdate);
        if (!flag) {
            return false;
        }
        //保存缓存
        redisService.set(users.getOpenid() + users.getDeviceId(), users);
        return true;
    }

    @Override
    public Map<String, Integer> toDayStatistics(Integer usId) {
        //每日任务
        EntityWrapper<AdRecord> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("us_id", usId);
        entityWrapper.eq("ar_callback", CallbackAdRecordEnum.CALLBACK_YES.getValue());
        DateUtils.getCurrentDayTime(entityWrapper, "create_time");
        int count = adRecordService.selectCount(entityWrapper);
        Map<String, Integer> map = new HashMap<>(3);
        sumDayRewardRecord(map, usId);
        map.put("day_reward_count", count);
        return map;
    }

    /**
     * 更新用户名
     *
     * @param users
     * @return
     */
    @Override
    public boolean updateNickname(Users users) {
        String nickName = users.getNickname();
        if (StrUtil.isEmpty(nickName)) {
            throw new BizException("用户名不能为空");
        }
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("nickname", nickName);
        int count = iUsersService.selectCount(entityWrapper);
        if (count > 0) {
            throw new BizException("用户名已存在");
        }
        Users usersUpdate = new Users();
        usersUpdate.setNickname(nickName);
        usersUpdate.setId(users.getId());
        redisService.set(users.getOpenid() + users.getDeviceId(), users);
        return iUsersService.updateById(usersUpdate);
    }

    @Override
    public Map<String, Object> queryTheCharts(Integer userId) {
        Map<String, Object> map = iUsersService.toProxyStatistics(userId);
        //邀请人创造的收益
        EntityWrapper<RewardRecord> rewardEntity = new EntityWrapper<>();
        rewardEntity.eq("us_id", userId);
        rewardEntity.isNotNull("pus_id");
        List<RewardRecord> rewardRecordList = rewardRecordService.selectList(rewardEntity);
        List<BizRankingList> rankingLists = new ArrayList<>();
        List<BizRankingList> todayList = new ArrayList<>();
        List<BizRankingList> monthList = new ArrayList<>();
        if (ObjectUtil.isNotNull(rewardRecordList)) {
            // 分组求和
            setUsersData(rewardRecordList, rankingLists, true);
            List<RewardRecord> monthRecordList = rewardRecordList.stream().filter(rewardRecord -> DateUtil.isSameMonth(rewardRecord.getCreateTime(), new Date())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(monthRecordList)) {
                setUsersData(monthRecordList, monthList, true);
            }
            List<RewardRecord> todayRecordList = rewardRecordList.stream().filter(rewardRecord -> DateUtil.isSameDay(rewardRecord.getCreateTime(), new Date())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(todayRecordList)) {
                setUsersData(todayRecordList, todayList, true);
            }
        }
        map.put("monthList", monthList);
        map.put("incomeList", rankingLists);
        map.put("todayList", todayList);
        return map;
    }

    @Override
    public List<BizRankingList> queryTheCharts(Integer userId, Integer index) {
        //邀请人创造的收益
        EntityWrapper<RewardRecord> rewardEntity = new EntityWrapper<>();
        rewardEntity.eq("us_id", userId);
        rewardEntity.isNotNull("pus_id");
        List<RewardRecord> rewardRecordList = rewardRecordService.selectList(rewardEntity);
        if (ObjectUtil.isNull(rewardRecordList)) {
            return new ArrayList<>();
        }
        // 分组求和
        List<BizRankingList> rankingLists = new ArrayList<>();
        switch (index) {
            case 2:
                rewardRecordList = rewardRecordList.stream().filter(rewardRecord -> DateUtil.isSameMonth(rewardRecord.getCreateTime(), new Date())).collect(Collectors.toList());
                break;
            case 3:
                rewardRecordList = rewardRecordList.stream().filter(rewardRecord -> DateUtil.isSameDay(rewardRecord.getCreateTime(), new Date())).collect(Collectors.toList());
                break;
            default:
                break;
        }
        if (ObjectUtil.isNull(rewardRecordList)) {
            return new ArrayList<>();
        }
        setUsersData(rewardRecordList, rankingLists, false);
        return rankingLists;

    }

    /**
     * 封装数据
     *
     * @param rewardRecordList
     * @param rankingLists
     * @param flag
     */
    private void setUsersData(List<RewardRecord> rewardRecordList, List<BizRankingList> rankingLists, boolean flag) {
        Map<Integer, Integer> groupSum = rewardRecordList.stream().collect(Collectors.groupingBy(RewardRecord::getPusId, Collectors.summingInt(RewardRecord::getRrMoney)));
        // 排序（升序）
        List<Map.Entry<Integer, Integer>> sortedGroupSum = groupSum.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toList());
        Collections.sort(sortedGroupSum, ((o1, o2) -> o2.getValue().compareTo(o1.getValue())));
        sortedGroupSum.forEach(entry -> {
            if (rankingLists.size() == 3 && flag) {
                return;
            }
            BizRankingList rankingList = new BizRankingList();
            rankingList.setId(String.valueOf(entry.getKey()));
            int index = rankingLists.size() + 1;
            rankingList.setIndex(String.valueOf(index));
            rankingList.setMoney(String.valueOf(entry.getValue()));
            rankingLists.add(rankingList);
        });
    }


    /**
     * 保证二维码的唯一性
     *
     * @return
     */
    private String isValidCode() {
        String code = RandomUtil.randomNumbers(8);
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        Users userEntity = new Users();
        userEntity.setCode(code);
        entityWrapper.setEntity(userEntity);
        Users users = iUsersService.selectOne(entityWrapper);
        if (ObjectUtil.isNull(users)) {
            return code;
        }
        return isValidCode();
    }

    /**
     * 保证用户名的唯一性
     *
     * @return
     */
    private String isValidNickName() {
        String nickname = RandomUtil.randomString(6);
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        Users userEntity = new Users();
        userEntity.setNickname(nickname);
        entityWrapper.setEntity(userEntity);
        Users users = iUsersService.selectOne(entityWrapper);
        if (ObjectUtil.isNull(users)) {
            return nickname;
        }
        return isValidNickName();
    }

    private void sumDayRewardRecord(Map<String, Integer> map, Integer usId) {
        EntityWrapper<RewardRecord> recordEntityWrapper = new EntityWrapper<>();
        recordEntityWrapper.eq("us_id", usId);
        DateUtils.getCurrentDayTime(recordEntityWrapper, "create_time");
        List<RewardRecord> rewardRecordList = rewardRecordService.selectList(recordEntityWrapper);
        if (ObjectUtil.isNotNull(rewardRecordList)) {
            List<RewardRecord> goldCoinsList = rewardRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_GOLD_COINS.getValue().equals(rewardRecord.getRrType())).collect(Collectors.toList());
            int sum = 0;
            if (ObjectUtil.isNotNull(goldCoinsList)) {
                sum = goldCoinsList.stream().mapToInt(RewardRecord::getRrMoney).sum();
            }
            List<RewardRecord> redEnvelopeList = rewardRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_RED_ENVELOPE.getValue().equals(rewardRecord.getRrType())).collect(Collectors.toList());
            int redEnvelopeSum = 0;
            if (ObjectUtil.isNotNull(redEnvelopeList)) {
                redEnvelopeSum = redEnvelopeList.stream().mapToInt(RewardRecord::getRrMoney).sum();
            }
            map.put(MoneyTypeEnum.MONEY_GOLD_COINS.getKey(), sum);
            map.put(MoneyTypeEnum.MONEY_RED_ENVELOPE.getKey(), redEnvelopeSum);
        }
        Users users = iUsersService.selectById(usId);
        User user = userMapper.selectUserByPlUserId(usId);
        if (ObjectUtil.isNotNull(user)) {
            map.put("isCheckProxy", 1);
        } else {
            map.put("isCheckProxy", 2);
        }
        map.put(MoneyTypeEnum.MONEY_COMMISSION_GOLD_COINS.getKey(), users.getMoneyCommissionGoldCoin());
        map.put(MoneyTypeEnum.MONEY_COMMISSION_RED_ENVELOPE.getKey(), users.getMoneyCommissionRedEnvelope());
        map.put(MoneyTypeEnum.MONEY_EXTENSION_RED_ENVELOPE.getKey(), users.getMoneyExtensionRedEnvelope());
    }

    /**
     * 双单请验证
     *
     * @param openid
     */
    private void verifyRiskControl(String openid, String day) {
        DateTime dateTime = DateUtil.offsetDay(new Date(), Integer.parseInt(day));
        Long strRe = (Long) redisService.get(openid);
        if (ObjectUtil.isEmpty(strRe)) {
            redisService.set(openid, dateTime.getTime());
            String formatTime = DateUtil.format(new Date(dateTime.getTime()), DateUtils.DATE_TIME_PATTERN);
            throw new RiskException("将于【" + formatTime + "】自动解除风控，感谢您的支持和信任");
        } else {
            long remainder = strRe - System.currentTimeMillis();
            if (remainder > 0) {
                String formatTime = DateUtil.format(new Date(strRe), DateUtils.DATE_TIME_PATTERN);
                throw new RiskException("将于【" + formatTime + "】自动解除风控，感谢您的支持和信任");
            }
        }
    }

    private void checkShuangQing(LoginVo loginVo) {
        Long firstInstallTim = loginVo.getFirstInstallTime();
        String shuangQing = (String) redisService.get(RedisEnum.RISK_SHUANG_QING.getKey()+loginVo.getUvChannel());
        if (StrUtil.isNotEmpty(shuangQing)) {
            DateTime dateTime = DateUtil.offsetDay(new Date(firstInstallTim), Integer.parseInt(shuangQing));
            if (dateTime.getTime() >= System.currentTimeMillis()) {
                String formatTime = DateUtil.format(new Date(dateTime.getTime()), DateUtils.DATE_TIME_PATTERN);
                throw new RiskException("将于【" + formatTime + "】自动解除风控，感谢您的支持和信任");
            }
        }
    }
}
